//
//  PPRegisterPetViewController.m
//  pet
//
//  Created by 陈无忌 on 11/23/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPRegisterPetTableViewController.h"
#import "supportingHeadFiles.h"
#import "PPCameraAuthorization.h"

@interface PPRegisterPetTableViewController ()<UIGestureRecognizerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *petAvatar;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (strong, nonatomic) NSString *filePathString;

@property (nonatomic) int gender;
@property (weak, nonatomic) IBOutlet UIButton *choseMaleButton;
@property (weak, nonatomic) IBOutlet UIButton *choseFemaleButton;

@property (strong, nonatomic) NSArray *petTypeArray;
@property (strong, nonatomic) NSArray *petBreedArray;

@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *typeTF;
@property (weak, nonatomic) IBOutlet UITextField *breedTF;
@property (weak, nonatomic) IBOutlet UITextField *ageTF;

@property (nonatomic, strong) UIPickerView *pickerView;
@property (strong, nonatomic) UIToolbar *toolBar;
@property (strong, nonatomic) UIBarButtonItem *cancelButton;
@property (strong, nonatomic) UIBarButtonItem *doneButton;

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (nonatomic, strong) UIToolbar *dateToolBar;
@property (nonatomic, strong) UIBarButtonItem *dateDoneButton;
@property (nonatomic, strong) UIBarButtonItem *dateCancelButton;
@property (nonatomic, strong) NSDateFormatter *formatter;

@property (nonatomic, weak) PPSystemConfiguraton *config;


@end

@implementation PPRegisterPetTableViewController
- (PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}
//date picker view
- (NSDateFormatter *)formatter
{
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [_formatter setTimeZone:timeZone];
        [_formatter setDateFormat:@"yyyy/MM/dd"];
    }
    return _formatter;
}
//UIDatePicker
- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
    }
    return _datePicker;
}
- (UIToolbar *)dateToolBar
{
    if (!_dateToolBar) {
        _dateToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.dateCancelButton, space, self.dateDoneButton, nil];
        [_dateToolBar setItems:toolBarItems];
    }
    return _dateToolBar;
}
- (UIBarButtonItem *)dateCancelButton
{
    if (!_dateCancelButton) {
        _dateCancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
    }
    return _dateCancelButton;
}
- (UIBarButtonItem *)dateDoneButton
{
    if (!_dateDoneButton) {
        _dateDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
    }
    return _dateDoneButton;
}

- (void)cancelDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.ageTF isFirstResponder]) {
        [self.ageTF resignFirstResponder];
    }
}
- (void)doneDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.ageTF isFirstResponder]) {
        [self.ageTF resignFirstResponder];
        self.ageTF.text = [self.formatter stringFromDate:self.datePicker.date];
    }
}


//pickerView
-(UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
    }
    return _pickerView;
}
-(UIToolbar *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.cancelButton, space, self.doneButton, nil];
        [_toolBar setItems:toolBarItems];
    }
    return _toolBar;
}
- (UIBarButtonItem *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];
    }
    return _cancelButton;
}
- (UIBarButtonItem *)doneButton
{
    if (!_doneButton) {
        _doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];
    }
    return _doneButton;
}

- (void)cancelButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.typeTF isFirstResponder]) {
        [self.typeTF resignFirstResponder];
    }else{
        [self.breedTF resignFirstResponder];
    }
    
}
- (void)doneButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.typeTF isFirstResponder]) {
        [self.typeTF resignFirstResponder];
        if (![self.typeTF.text isEqualToString:[self.petTypeArray objectAtIndex:[self.pickerView selectedRowInComponent:0]]]) {
            self.breedTF.text = @"";
        }
        self.typeTF.text = [self.petTypeArray objectAtIndex:[self.pickerView selectedRowInComponent:0]];
        self.petBreedArray = [PPPetTypeArrayList getBreedWithType:[NSString stringWithFormat:@"%@",self.typeTF.text]];
        
    }else{
        [self.breedTF resignFirstResponder];
        self.breedTF.text = [self.petBreedArray objectAtIndex:[self.pickerView selectedRowInComponent:0]];
    }
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.scrollEnabled = NO;
    [self.navigationItem setHidesBackButton:YES];
    
    [self.choseMaleButton addTarget:self action:@selector(choseMale:) forControlEvents:UIControlEventTouchUpInside];
    [self.choseFemaleButton addTarget:self action:@selector(choseFemale:) forControlEvents:UIControlEventTouchUpInside];
    self.choseMaleButton.tag = 0;
    self.choseFemaleButton.tag = 1;
    
    self.gender = 0;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
    
    UITapGestureRecognizer *imageRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseImage)];
    self.petAvatar.userInteractionEnabled = YES;
    imageRecognizer.numberOfTouchesRequired = 1;
    imageRecognizer.numberOfTapsRequired = 1;
    [self.petAvatar addGestureRecognizer:imageRecognizer];
    
    self.nameTF.delegate = self;
    self.typeTF.delegate = self;
    self.breedTF.delegate = self;
    self.ageTF.delegate = self;
    
    self.typeTF.inputView = self.pickerView;
    self.typeTF.inputAccessoryView = self.toolBar;
    self.breedTF.inputView = self.pickerView;
    self.breedTF.inputAccessoryView = self.toolBar;
    
    self.ageTF.inputView = self.datePicker;
    self.ageTF.inputAccessoryView = self.dateToolBar;
    
    self.petTypeArray = [PPPetTypeArrayList getType];
    
    
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)chooseImage
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.tableView];
}

#pragma mark - ActionSheet
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }else if (buttonIndex == 1) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (IS_OS_7_OR_LATER) {
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }

        }else{
            [self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];}

#pragma mark - UIImagePickContrillerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    [self.petAvatar setImage:image];
    self.filePathString = [self uploadUserAvatar:self.petAvatar.image];
    image = nil;
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)uploadUserAvatar:(UIImage *)image
{
    NSData *data;
    if (UIImagePNGRepresentation(image).length > 2100000) {
        data = UIImageJPEGRepresentation(image, 0.5);
    }else{
        data = UIImagePNGRepresentation(image);
    }
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/userAvatar.png"] contents:data attributes:nil];
    //得到选择后沙盒中图片的完整路径 并返回
    return [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/userAvatar.png"];
}

#pragma mark - Custom IBAction
- (IBAction)savePet:(id)sender {
    //first step check
    if (!self.nameTF.text.length > 0) {
        [self alertShow:@"请输入宠物的名字！"];
        return;
    }
    if (!self.ageTF.text.length > 0) {
        [self alertShow:@"请输入宠物的生日！"];
        return;
    }
    if (!self.typeTF.text.length > 0) {
        [self alertShow:@"请设置宠物的类型！"];
        return;
    }
    if (!self.breedTF.text.length > 0) {
        [self alertShow:@"请设置宠物的种族！"];
        return;
    }
    [HUD showUIBlockingIndicatorWithText:@"正在创建"];
    NSString *breeding = @"no";
    NSString *url = [PPAPIList getAPIList].PPSaveOrUpdatePetMsg;
    NSDictionary *params = @{@"userId":@(self.userId),@"birth":self.ageTF.text,@"petName":self.nameTF.text,@"petType":self.typeTF.text,@"petBreed":self.breedTF.text,@"petGender":@(self.gender),@"breeding":breeding};
    [httpRequst POST:url parameters:params imagePath:self.filePathString imageName:@"petAvatar" keyWords:@"petAvatar" success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSLog(@"%@",responseObject);
        NSNumber *value = responseObject[@"processResult"];
        if (value.boolValue) {
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self alertShow:@"添加宠物失败，请重试"];
        }
        [HUD hideUIBlockingIndicator];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [HUD hideUIBlockingIndicator];
    }];
}

- (void)choseMale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
}

- (void)choseFemale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"femaleBig"] forState:UIControlStateNormal];
}


#pragma mark - Pick view data soure
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView//返回选择器组件数
{
    return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component//选择器的选项个数
{
    if ([self.typeTF isFirstResponder]) {
        return self.petTypeArray.count;
    }else{
        return self.petBreedArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([self.typeTF isFirstResponder]) {
        return [self.petTypeArray objectAtIndex:row];
    }else{
        return [self.petBreedArray objectAtIndex:row];
    }
}

#pragma mark - UITextFiled delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.typeTF]) {
        [self.pickerView reloadAllComponents];
        
    }else if ([textField isEqual:self.breedTF]){
        if (self.typeTF.text.length == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先设置宠物类型" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
            [alert show];
            return NO;
        }
        [self.pickerView reloadAllComponents];
    }else if ([textField isEqual:self.ageTF]) {
        [self.datePicker setDatePickerMode:UIDatePickerModeDate];
        [self.datePicker setMaximumDate:[NSDate date]];
        [self.datePicker setMinimumDate:nil];
        [self.formatter setDateFormat:@"yyyy/MM/dd"];
        NSDate *currentDate;
        if (textField.text.length > 0) {
            currentDate = [self.formatter dateFromString:self.ageTF.text];
        }else{
            currentDate = [NSDate date];
        }
        [self.datePicker setDate:currentDate];
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - Custom Method
-(void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

#pragma mark - UITable View delegate
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
